package com.pangu.web.handler.admin.platform;

import java.util.*;


import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.github.wenhao.jpa.Specifications;
import com.pangu.core.BMDataContext;
import com.pangu.util.GameUtils;
import com.pangu.util.disruptor.DisruptorHandler;
import com.pangu.web.handler.admin.annotation.OpeLog;
import com.pangu.web.handler.admin.utils.page.Pagination;
import com.pangu.web.service.GameUserService;
import com.pangu.web.service.repository.es.PlayUserESRepository;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.pangu.util.Menu;
import com.pangu.web.handler.Handler;
import com.pangu.web.model.PlayUser;
import com.pangu.web.service.repository.jpa.PlayUserRepository;

@Controller
@RequestMapping("/apps/platform")
public class GameUsersController extends Handler {


    @Autowired
    private PlayUserESRepository playUserESRes;

    @Autowired
    private PlayUserRepository playUserRes;

    @Autowired
    private PlayUserRepository playUserRepository;

    @Autowired
    private GameUserService gameUserService;


    /**
     * @author Chris
     * @date 2018/4/11 18:33
     * @todo 查询玩家
     */
    @RequestMapping({"/gameusers"})
    @RequiresPermissions("sys:member:select")
    public String getPlayUser(String findContent, ModelMap modelMap, Integer pageNo, Integer pageSize, HttpServletRequest request, @Valid PlayUser playUser) {
        modelMap.put("findContent", findContent);
        if (pageSize == null) {
            pageSize = 25;
        }
        if (StringUtils.isNotBlank(playUser.getUsername())) {
            modelMap.addAttribute("username", playUser.getUsername());
        }
        if (playUser.getMinGoldCoins() != null) {
            modelMap.addAttribute("minGoldCoins", playUser.getMinGoldCoins());
        }
        if (playUser.getMaxGoldCoins() != null) {
            modelMap.addAttribute("maxGoldCoins", playUser.getMaxGoldCoins());
        }
        String view;
        int total;
        int online;
        if(playUser.getPlayertype()!=null&&playUser.getPlayertype().equals("normal")){
            total=playUserRepository.countByOrgiAndPlayertype(super.getOrgi(request),"normal");
            online=playUserRepository.countByOrgiAndPlayertypeAndOnline(super.getOrgi(request),"normal",true);
            view="/platform/game/playUser";
            }else {
            total=playUserRepository.countByOrgiAndPlayertype(super.getOrgi(request),"ai");
            online=playUserRepository.countByOrgiAndPlayertypeAndOnline(super.getOrgi(request),"ai",true);
            view="/platform/game/ai";
        }
         Pagination pagination=gameUserService.getPlayUser(playUser,pageNo,pageSize);
         modelMap.put("playUserList",pagination.getList());
         modelMap.put("page",pagination.getPageHtml());

         modelMap.put("total",total);
         modelMap.put("online",online);
        return view;
    }

  /*  @RequestMapping({"/ai"})
    @RequiresPermissions("sys:ai:select")
    public ModelAndView getAi(ModelMap map, HttpServletRequest request, @Valid PlayUser playUser) {
        if (StringUtils.isNotBlank(playUser.getUsername())) {
            map.addAttribute("username", playUser.getUsername());
        }
        if (playUser.getMinGoldCoins() != null) {
            map.addAttribute("minGoldCoins", playUser.getMinGoldCoins());
        }
        if (playUser.getMaxGoldCoins() != null) {
            map.addAttribute("maxGoldCoins", playUser.getMaxGoldCoins());
        }
        Specification<PlayUser> specification = Specifications.<PlayUser>and()
                .eq("playertype", "ai")
                .eq(StringUtils.isNotBlank(playUser.getOrgi()), "orgi", playUser.getOrgi())
                .eq(StringUtils.isNotBlank(playUser.getUsername()), "username", playUser.getUsername())
                .eq(playUser.isOnline(), "online", playUser.isOnline())
                .between(playUser.getMaxGoldCoins() != null && playUser.getMinGoldCoins() != null, "goldcoins", playUser.getMinGoldCoins(), playUser.getMaxGoldCoins())
                .build();
        int p=super.getP(request);
        int ps=super.getPs(request);
        Page<PlayUser> page = playUserRepository.findAll(specification, new PageRequest(p,ps));
        //查询当前在线
        int online = playUserRepository.countByOrgiAndPlayertypeAndOnline("beimi", "ai", true);
        map.addAttribute("online", online);

        map.addAttribute("aiList", page);
        return request(super.createAppsTempletResponse("/platform/game/ai/aiList"));
    }*/

    @RequestMapping({"/ai"})
    @RequiresPermissions("sys:ai:select")
    public ModelAndView getAi(ModelMap map, HttpServletRequest request, @Valid PlayUser playUser) {

        if (StringUtils.isNotBlank(playUser.getUsername())) {
            map.addAttribute("username", playUser.getUsername());
        }
        if (playUser.getMinGoldCoins() != null) {
            map.addAttribute("minGoldCoins", playUser.getMinGoldCoins());
        }
        if (playUser.getMaxGoldCoins() != null) {
            map.addAttribute("maxGoldCoins", playUser.getMaxGoldCoins());
        }
        Specification<PlayUser> specification = Specifications.<PlayUser>and()
                .eq("playertype", "ai")
                .eq(StringUtils.isNotBlank(playUser.getOrgi()), "orgi", playUser.getOrgi())
                .eq(StringUtils.isNotBlank(playUser.getUsername()), "username", playUser.getUsername())
                .eq(playUser.isOnline(), "online", playUser.isOnline())
                .between(playUser.getMaxGoldCoins() != null && playUser.getMinGoldCoins() != null, "goldcoins", playUser.getMinGoldCoins(), playUser.getMaxGoldCoins())
                .build();
        int p=super.getP(request);
        int ps=super.getPs(request);
        Page<PlayUser> page = playUserRepository.findAll(specification, new PageRequest(p,ps));
        //查询当前在线
        int online = playUserRepository.countByOrgiAndPlayertypeAndOnline("beimi", "ai", true);
        map.addAttribute("online", online);

        map.addAttribute("aiList", page);
        return request(super.createAppsTempletResponse("/platform/game/ai/aiList"));
    }


    @RequestMapping({"/gameusers/online"})
    @Menu(type = "platform", subtype = "onlinegameusers")
    public ModelAndView online(ModelMap map, HttpServletRequest request, @Valid String id) {
        map.addAttribute("playersList", playUserRepository.findByOrgiAndOnline(super.getOrgi(request), true, new PageRequest(super.getP(request), super.getPs(request))));
        return request(super.createAppsTempletResponse("/platform/game/online/index"));
    }

    @RequestMapping({"/gameusers/edit"})

    public ModelAndView edit(ModelMap map, HttpServletRequest request, @Valid String id) {
        map.addAttribute("playUser", playUserRepository.findById(id));
        return request(super.createRequestPageTempletResponse("/platform/game/data/edit"));
    }

    @RequestMapping("/gameusers/update")
    @Menu(type = "admin", subtype = "gameusers")
    public ModelAndView update(HttpServletRequest request, @Valid PlayUser players) {
        PlayUser playUser = playUserRepository.findById(players.getId());
        if (playUser != null) {
            playUser.setDisabled(players.isDisabled());
            playUser.setGoldcoins(players.getGoldcoins());
			/*playUser.setCards(players.getCards());
			playUser.setDiamonds(players.getDiamonds());*/
            playUser.setUpdatetime(new Date());
            playUserRepository.save(playUser);
            playUserRes.save(playUser);
        }
        return request(super.createRequestPageTempletResponse("redirect:/apps/platform/gameusers.html"));
    }


    /**
     * @author Chris
     * @date 2018/4/5 19:26
     * @todo 新增AI
     */
    @RequestMapping({"/add/ai"})
    @RequiresPermissions("sys:ai:add")
    public ModelAndView addAi(ModelMap map, HttpServletRequest request) {
        //查询在线的AI玩家 ，以及AI玩家的数量等信息
        int aiTotal = playUserRepository.countByOrgiAndPlayertype(super.getOrgi(request), "ai");
        int onlineTotal = playUserRepository.countByOrgiAndPlayertypeAndOnline(super.getOrgi(request), "ai", true);
        map.addAttribute("aiTotal", aiTotal);
        map.addAttribute("onlineTotal", onlineTotal);
        return request(super.createAppsTempletResponse("/platform/game/ai/add"));
    }

    /**
     * @author Chris
     * @date 2018/4/6 14:33
     * @todo 批量创建Ai玩家
     */
    @RequestMapping({"/create/ai"})
    @ResponseBody
    @RequiresPermissions("sys:ai:add")
    public Map<String, Object> createAi(String times) {
        Map<String, Object> resultMap = new HashMap<>();
        int i = 0;
        try {
            while (i < Integer.parseInt(times)) {
                PlayUser player = new PlayUser();
                GameUtils.createAI(player, BMDataContext.PlayerTypeEnum.AI.toString());
                int users = playUserESRes.countByUsername(player.getUsername());
                DisruptorHandler.published(player, playUserESRes, playUserRes);
                i++;
            }
            resultMap.put("message", "新增成功");
        } catch (NumberFormatException e) {
            resultMap.put("message",e.getMessage());
            e.printStackTrace();
        }

        return resultMap;
    }

    /**
     * @author Chris
     * @date 2018/5/19 13:45
     * @todo   禁用/启用
    */
    @OpeLog("禁用/启用玩家")
    @RequestMapping(value = "/disable")
    @ResponseBody
    @RequiresPermissions("sys:user:update")
    public Map<String,Object> disable(@Valid String id,HttpServletRequest request){
       System.out.println("需要禁用的id"+id);
       // 通过ID查
        try {
            PlayUser playUser=playUserRepository.findById(id);
            if(playUser!=null){
                if(playUser.isDisabled()){
                  playUser.setDisabled(false);
                }else {
                    playUser.setDisabled(true);
                }

            }
            playUserRepository.save(playUser);
            resultMap.put("message","禁用/启用成功");
        } catch (Exception e) {
            resultMap.put("message",e.getMessage());
            e.printStackTrace();
        }


        return resultMap;
    }

}
